package com.pb.camera.fragment;

import java.util.List;
import java.util.Map;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.pb.camera.R;
import com.pb.camera.adapter.HomePageViewPagerAdapter;
import com.pb.camera.application.App;
import com.pb.camera.bean.AllRoom;
import com.pb.camera.bean.Room;
import com.pb.camera.h264.PlayCurrentViewActivity;
import com.pb.camera.jph.activity.AddCameraNoticeActivity;
import com.pb.camera.utils.JsonAnalyle;
import com.pb.camera.utils.JsonUtil;
import com.pb.camera.utils.Url;
import com.pb.camera.view.TabPageIndicator;
//import com.tencent.mm.sdk.modelbase.BaseResp.ErrCode;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ActionBar.LayoutParams;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class HomeFragment extends Fragment implements OnClickListener {
    private ViewPager viewPager;
    private HomePageViewPagerAdapter adapter;
    private TabPageIndicator indicator;
    private Dialog homeManagerDialog;
    private AnimationDrawable an;
    private Dialog progressDialog;
    private Dialog newHomeDialog;
    private Dialog replaceNameDialog;
    private Dialog deleteHomeDialog;
    private ImageView image_home_manager;
    /**
     * 新建的房间或重命名的房间
     * 重命名的设备的名字
     */
    private String newHomeName;

    /**
     * 0代表添加房间,1代表重命名房间
     */
    private int diaologOperate;
    private List<Room> rooms;
    private HttpUtils httpUtils;
    /**
     * 所有的房间
     */
    private List<Room> selfRooms;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        httpUtils = new HttpUtils();
        showProgressDialog();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.home_fragment, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        ImageView image = (ImageView) view.findViewById(R.id.home_page_add_device);
        image.setOnClickListener(this);
        viewPager = (ViewPager) view.findViewById(R.id.home_page_viewpager);
        indicator = (TabPageIndicator) view.findViewById(R.id.home_page_indicator);
        adapter = new HomePageViewPagerAdapter(getChildFragmentManager(), selfRooms);
        viewPager.setAdapter(adapter);
        indicator.setViewPager(viewPager);
        image_home_manager = (ImageView) view.findViewById(R.id.home_page_homemanager);
        image_home_manager.setOnClickListener(this);
        String url = Url.selectAllGroups(App.getInstance().getUserId(), 0);
        getAllRoom(url, 0);
    }

    /**
     * 创建管理房间的对话框
     *
     * @return
     */
    private Dialog createHomeMangerDialog() {
        if (homeManagerDialog == null) {
            homeManagerDialog = new Dialog(getActivity(), R.style.dialog);
            homeManagerDialog.show();
            WindowManager.LayoutParams lp = homeManagerDialog.getWindow().getAttributes();
            lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            homeManagerDialog.setContentView(R.layout.home_manager_dialog);
            View view = homeManagerDialog.getWindow().getDecorView();
            View view_root = view.findViewById(R.id.home_manager_root);
            ImageView image_add = (ImageView) view.findViewById(R.id.home_manager_add_home);
            ImageView image_delete = (ImageView) view.findViewById(R.id.home_manager_delete_home);
            ImageView image_rename = (ImageView) view.findViewById(R.id.home_manager_rename_home);
            TextView text_delete = (TextView) view.findViewById(R.id.home_manager_text_delete_home);
            TextView text_rename = (TextView) view.findViewById(R.id.home_manager_text_rename_home);
            image_add.setOnClickListener(this);
            image_delete.setOnClickListener(this);
            image_rename.setOnClickListener(this);
            ViewHolder holder = new ViewHolder();
            holder.text_delete = text_delete;
            holder.text_rename = text_rename;
            view_root.setTag(holder);

        }
        return null;
    }

    /**
     * 弹出管理房间的对话框
     *
     * @param homeName
     */
    private void showHomeManagerDialog(String homeName) {
        if (homeManagerDialog == null) {
            createHomeMangerDialog();
        } else {
            View view = homeManagerDialog.getWindow().getDecorView();
            View view_root = view.findViewById(R.id.home_manager_root);
            ViewHolder holder = (ViewHolder) view_root.getTag();
            if (homeName == null || homeName.equals("")) {
                homeName = "房间";
            }
            holder.text_delete.setText("删除" + homeName);
            holder.text_rename.setText("重命名" + homeName);
            if (!homeManagerDialog.isShowing()) {
                homeManagerDialog.show();
            }
        }
    }


    private void createNewHomeDialog() {
        newHomeDialog = new Dialog(getActivity(), R.style.dialog);
        newHomeDialog.show();

        WindowManager.LayoutParams p = newHomeDialog.getWindow().getAttributes(); // 获取对话框当前的参数值
//	    p.height = (int) (d.getHeight() * 0.28); // 高度设置为屏幕的0.3
        p.height = LayoutParams.WRAP_CONTENT;
        p.gravity = Gravity.CENTER;
        p.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.8); // 宽度设置为屏幕的0.8
        newHomeDialog.getWindow().setAttributes(p);
        newHomeDialog.setContentView(R.layout.dialog_replace_room_name);
        final EditText ed = (EditText) newHomeDialog.getWindow().getDecorView().findViewById(R.id.et_roomname);
        TextView cancle = (TextView) newHomeDialog.getWindow().getDecorView().findViewById(R.id.bt_cancel);
        cancle.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                newHomeDialog.dismiss();
            }
        });
        TextView certain = (TextView) newHomeDialog.getWindow().getDecorView().findViewById(R.id.bt_submit);
        certain.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String name = ed.getText().toString();
                if (name == null || name.equals("")) {
                    Toast.makeText(getActivity(), "房间名不可以是空", Toast.LENGTH_SHORT).show();
                } else {
                    //保存输入的房间的名字
                    newHomeName = name;
                    //开始修改名字
                    nameOperate(name, 0);
//		     editNameDialog.dismiss();
                }
            }
        });
    }

    /**
     * 添加新的房间
     */
    private void showNewHomeDiaolog() {
        if (newHomeDialog == null) {
            createNewHomeDialog();
        } else {
            if (!newHomeDialog.isShowing()) {
                newHomeDialog.show();
            }
        }

    }

    private void createReplaceHomeDialog() {
        replaceNameDialog = new Dialog(getActivity(), R.style.dialog);
        replaceNameDialog.show();

        WindowManager.LayoutParams p = replaceNameDialog.getWindow().getAttributes(); // 获取对话框当前的参数值
//		    p.height = (int) (d.getHeight() * 0.28); // 高度设置为屏幕的0.3
        p.height = LayoutParams.WRAP_CONTENT;
        p.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.8); // 宽度设置为屏幕的0.8
        p.gravity = Gravity.CENTER;
        replaceNameDialog.getWindow().setAttributes(p);
        replaceNameDialog.setContentView(R.layout.dialog_replace_room_name);
        TextView tv_delete = (TextView) replaceNameDialog.getWindow().getDecorView().findViewById(R.id.tv_delete);
        tv_delete.setText("重命名房间");
        final EditText ed = (EditText) replaceNameDialog.getWindow().getDecorView().findViewById(R.id.et_roomname);
        TextView cancle = (TextView) replaceNameDialog.getWindow().getDecorView().findViewById(R.id.bt_cancel);
        cancle.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                replaceNameDialog.dismiss();
            }
        });
        TextView certain = (TextView) replaceNameDialog.getWindow().getDecorView().findViewById(R.id.bt_submit);
        certain.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String name = ed.getText().toString();
                if (name == null || name.equals("")) {
                    Toast.makeText(getActivity(), "房间名不可以是空", Toast.LENGTH_SHORT).show();
                } else {
                    //保存输入的房间的名字
                    newHomeName = name;
                    //开始修改名字
                    nameOperate(name, 1);
//		     editNameDialog.dismiss();
                }
            }
        });
    }

    /**
     * 修改房间的名字
     */
    private void showReplaceHomeDiaolog() {
        if (replaceNameDialog == null) {
            createReplaceHomeDialog();
        } else {
            if (!replaceNameDialog.isShowing()) {
                replaceNameDialog.show();
            }
        }

    }

    private void createDeleteHomeDialog() {
        deleteHomeDialog = new Dialog(getActivity(), R.style.dialog);

        deleteHomeDialog.show();

        WindowManager.LayoutParams p = deleteHomeDialog.getWindow().getAttributes(); // 获取对话框当前的参数值
//	    p.height = (int) (d.getHeight() * 0.28); // 高度设置为屏幕的0.3
        p.height = LayoutParams.WRAP_CONTENT;
        p.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.8); // 宽度设置为屏幕的0.8
        p.gravity = Gravity.CENTER;
        deleteHomeDialog.getWindow().setAttributes(p);
        deleteHomeDialog.setContentView(R.layout.dialog_delete_room);
        TextView cancle = (TextView) deleteHomeDialog.getWindow().getDecorView().findViewById(R.id.bt_cancel);
        TextView certain = (TextView) deleteHomeDialog.getWindow().getDecorView().findViewById(R.id.bt_submit);
        cancle.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                deleteHomeDialog.dismiss();
            }
        });
        certain.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                deleteRoom();
            }
        });
    }

    /**
     * 确认删除房间的对话框
     */
    private void showDeleteHomeDialog() {
        if (deleteHomeDialog == null) {
            createDeleteHomeDialog();
        } else {
            if (!deleteHomeDialog.isShowing()) {
                deleteHomeDialog.show();
            }
        }
    }

    /**
     * 网络访问的时候弹出的旋转对话框
     */
    private void createProgressDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),
                R.style.dialog);
        progressDialog = builder.create();
        progressDialog.show();
        progressDialog.setContentView(R.layout.rotate_image_view);
        ImageView imageView = (ImageView) progressDialog.getWindow().getDecorView()
                .findViewById(R.id.dialog_rotate_drawable);
        an = (AnimationDrawable) imageView.getDrawable();
        an.start();
    }

    /**
     * 展示progressdiaog
     */
    private void showProgressDialog() {
        if (progressDialog == null) {
            createProgressDialog();
        } else if (!progressDialog.isShowing()) {
            progressDialog.show();
            an.start();
        }
    }

    private void dismissProgressDialog() {
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
            an.stop();
        }

    }

    /**
     * 修改房间,新建房间的名字
     */
    private void nameOperate(String name, int diaologOperate) {
        /**
         * 0代表添加房间,1代表重命名房间
         */
        if (diaologOperate == 0) {
            addRoom(name);
        } else if (diaologOperate == 1) {
            renameRoom(name);
        }
    }

    private class ViewHolder {
        TextView text_delete;
        TextView text_rename;
    }

    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        switch (view.getId()) {
            case R.id.home_manager_add_home:
                //editnamediaolog编辑的是添加房间的名字
                diaologOperate = 0;
                showNewHomeDiaolog();
                break;
            case R.id.home_manager_delete_home:
                showDeleteHomeDialog();
                break;
            case R.id.home_manager_rename_home:
                //editnamediaolog编辑的是重命名房间的名字
                diaologOperate = 1;
                showReplaceHomeDiaolog();
                break;
            case R.id.home_page_homemanager:
                int pos = viewPager.getCurrentItem();
                Log.i("123", "pos" + pos);
                //弹出房间管理的对话框
                int count = adapter.getCount();
                if (count == 0) {
                    showHomeManagerDialog("");
                } else {
                    String title = (String) adapter.getPageTitle(pos);
                    showHomeManagerDialog(title);
                }

                break;
            case R.id.home_page_add_device:
                //添加设备
                Intent intentC = new Intent(getActivity(), AddCameraNoticeActivity.class);
                intentC.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            	//视频播放画面
            	//Intent intentP = new Intent(getActivity(), PlayCurrentViewActivity.class);
                startActivity(intentC);
                break;
            default:
                break;
        }
    }


    /**
     * 返回当前显示的房间.便于删除,添加,重命名的操作
     */
    private Room getCurrentSelectedRoom() {
        return rooms.get(viewPager.getCurrentItem());
    }

    /**
     * 删除房间
     */
    private void deleteRoom() {
        //需要的是跳转到添加的界面吗
        if (adapter.getCount() == 0) {
            Toast.makeText(getActivity(), "当前房间无效", Toast.LENGTH_SHORT).show();
        } else {
            String path = Url.deleteGroup(rooms.get(viewPager.getCurrentItem()).getGids(), App.getInstance().getUserId());
            homeOperateThrowNet(path, 1, getActivity(), rooms.get(viewPager.getCurrentItem()).getGids() + "");
        }


    }

    /**
     * 添加房间
     */
    private void addRoom(String homeName) {
        String path = Url.createGroup(homeName, App.getInstance().getUserId());
        homeOperateThrowNet(path, 0, getActivity(), homeName);
    }

    /**
     * 重命名房间
     */
    private void renameRoom(String newName) {
        if (adapter.getCount() == 0) {
            Toast.makeText(getActivity(), "当前房间无效", Toast.LENGTH_SHORT).show();
        } else {
            //需要的是跳转到重命名的界面吗
            String gNum = rooms.get(viewPager.getCurrentItem()).getGids() + "";
            String path = Url.replaceGroupName(gNum, newName);
            homeOperateThrowNet(path, 2, getActivity(), null);
        }
    }

    /**
     * @param path
     * @param order               0是添加房间,1是删除,2是重命名房间
     * @param ac
     * @param deleteORAddHomeName 删传值是房间的id添加的时候是房间的名字
     */
    private void homeOperateThrowNet(String path, final int order, final Activity ac, final String deleteORAddHomeName) {
        showProgressDialog();
        httpUtils.send(HttpMethod.POST, path, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
                Toast.makeText(getActivity(), "网络访问失败", Toast.LENGTH_SHORT).show();
                dismissProgressDialog();
            }

            @Override
            public void onSuccess(final ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
                boolean flag = JsonAnalyle.jsonAnalyse(arg0.result, ac, null, null);
                if (flag) {
                    ac.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            if (order == 0) {
                                Map<String, Object> map = JsonAnalyle.addRoom(arg0.result);
                                handleAddRoomOutcome(map);
                                dismissProgressDialog();
                            } else if (order == 1) {
                                handleChangeRoomOutcome(order, deleteORAddHomeName);
                                dismissProgressDialog();
                            } else if (order == 2) {
                                handleChangeRoomOutcome(order, deleteORAddHomeName);
                                dismissProgressDialog();
                            }
                        }
                    });

                } else {
                    dismissProgressDialog();
                }

            }
        });

    }


/**
 *
 */
    /**
     * 处理通过网络修改,删除,重名房间之后返回的结果
     *
     * @param order
     * @param homeid删除房间的时候传递的房间的id
     */
    private void handleChangeRoomOutcome(int order, String homeid) {
        if (order == 1) {
            roomChangeDelete(homeid);
        } else if (order == 2) {
            roomChangeDelete(homeid);
        }
    }

    public void initRooms(List<Room> rooms) {
        this.rooms = rooms;
    }


    /**
     * 添加房间成功之后的处理方法
     *
     * @param map
     */
    private void handleAddRoomOutcome(Map<String, Object> map) {
        Room newRoom = new Room();
        int gid = Integer.parseInt(map.get("gid").toString());
        newRoom.setGids(gid);
        newRoom.setName(map.get("gname").toString());
        rooms.add(newRoom);
        adapter.notifyDataSetChanged();
        indicator.notifyDataSetChanged();

    }


    /**
     * 删除房间成功之后调用的,不需要再次访问网络了,直接删除在本地删除就可以了
     *
     * @param homeid
     */
    private void roomChangeDelete(String homeid) {
        int deleteId = Integer.parseInt(homeid);
        for (Room r : rooms) {
            int id = r.getGids();
            if (id == deleteId) {
                rooms.remove(r);
                adapter.notifyDataSetChanged();
                indicator.notifyDataSetChanged();
                break;
            }
        }
    }

///**删除设备的时候
// * @param homeName
// * @param deviceId
// */
//private  void  roomChangeDeleteDevice(String homeName,String deviceId)
//{
//    for(Room r:rooms)
//    {
//    	if( r.getName().equals(homeName))
//    	{ 
//    		for (DeviceMode de:r.device) {
//				if (de.getDevid().equals(deviceId)) {
//					r.device.remove(de);
//				}
//			}
//    		rooms.remove(r);
//    	    adapter.notifyDataSetChanged();    	
//    	 break;
//    	}
//   	 break;
//    }
//}

    /**
     * 获取有的房间
     * 但是没有获取设备呢
     *
     * @param url
     * @param mode
     */
    private void getAllRoom(String url, int mode) {
        httpUtils.send(HttpMethod.POST, url, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
                Toast.makeText(getActivity(), "网络访问失败,请检查你的网络", Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
                Log.i("123", "所有的房间" + arg0.result);
                final AllRoom allRoom = JsonUtil.parseJsonToBean(arg0.result, AllRoom.class);
                if (allRoom.getData() == null) {
                    Log.i("123", "空");
                }

                if (allRoom.getErrcode().equals("0")) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            if (allRoom != null && allRoom.getData() != null && allRoom.getData().size() > 0) {
                                selfRooms = allRoom.getData();
                                progressDialog.dismiss();
                                //	adapter=new HomePageViewPagerAdapter(getChildFragmentManager(),selfRooms);
                                adapter.setRooms(selfRooms);
                                adapter.notifyDataSetChanged();
                                indicator.notifyDataSetChanged();
//						viewPager.setAdapter(adapter);
//					    indicator.setViewPager(viewPager);
                                //indicator.notifyDataSetChanged();
                                progressDialog.dismiss();
                            } else {
                                progressDialog.dismiss();
                            }
                        }
                    });
                } else {
                    String err = JsonAnalyle.getErrcode(arg0.result, null);
                    if (err.equals("-1")) {
                        Toast.makeText(getActivity(), "系统繁忙", Toast.LENGTH_SHORT).show();
                    }
                    progressDialog.dismiss();
                }
            }
        });
    }

    /**
     * 更新全部的房间,还有对用的设备信息,因为只是添加房间的话,不知道房间的标示值
     */
    public void updateAllRoomAndDevice(List<Room> roomList) {

        this.rooms = roomList;
        //   adapter.resetRoomData(roomList);
        adapter.notifyDataSetChanged();
        indicator.notifyDataSetChanged();
    }
}
